package org.example.day03;

/**
 * 第二章节2.1.7①synchronized修饰实例方法，可以将锁看成this对象，A线程获取锁，A释放之前B线程就拿不到锁，进不去方法了。
 *              ②当A线程出现异常时，会自动释放锁。
 **/
public class MyThread10 {
    synchronized public void testMethod(){
        if(Thread.currentThread().getName().equals("a")){
            System.out.println("ThreadName = " + Thread.currentThread().getName() + " beginTime = " + System.currentTimeMillis());
//            int i = 1;
//            while(i == 1){
//                if (("" + Math.random()).substring(0,8).equals("0.123456")){
//                    System.out.println("ThreadName = " + Thread.currentThread().getName());
//                    System.out.println("run exceptionTime = " + System.currentTimeMillis());
//                    Integer.parseInt("a");
//                }
//            }
            try {
                Thread.sleep(500000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("Thread B runTime = " + System.currentTimeMillis());
        }
    }

    public static void main(String[] args) {
        try {
            MyThread10 m10 = new MyThread10();
            Thread10A ta = new Thread10A(m10);
            ta.setName("a");
            ta.start();
            Thread.sleep(500);
            Thread10B tb = new Thread10B(m10);
            tb.setName("b");
            tb.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Thread10A extends Thread{
    private MyThread10 m10;

    public Thread10A(MyThread10 m10) {
        this.m10 = m10;
    }

    @Override
    public void run() {
        m10.testMethod();
    }
}
class Thread10B extends Thread{
    private MyThread10 m10;

    public Thread10B(MyThread10 m10) {
        this.m10 = m10;
    }
    @Override
    public void run() {
        m10.testMethod();
    }
}